#include <iostream>
#include <fstream> // 文件流
#include "contacts.pb.h"

void PrintContacts(contacts2::Contacts& contacts)
{
    for (int i = 0; i < contacts.contacts_size(); ++i)
    {
        std::cout << "------联系人 " << i + 1 << "------" << std:: endl;
        const contacts2::PeopleInfo people = contacts.contacts(i);
        std::cout << "姓名：" << people.name() << std::endl;
        std::cout << "年龄：" << people.age() << std::endl;
        for (int j = 0; j < people.phone_size(); ++j)
        {
            const contacts2::PeopleInfo_Phone phone = people.phone(j);
            std::cout <<  "电话 " << j + 1 << ": " << phone.number();
            std::cout << " (" << phone.PhoneType_Name(phone.type()) << ")" << std::endl;
        }
        // Any对象设置了值，并且类型是contacts2::Address
        if (people.has_data() && people.data().Is<contacts2::Address>()) 
        {
            contacts2::Address address;
            people.data().UnpackTo(&address);// 拿到address
            if (!address.home_address().empty()) {
                std::cout << "家庭地址：" << address.home_address() << std::endl;
            }
            if (!address.company_address().empty()) {
                std::cout << "公司地址：" << address.company_address() << std::endl;
            }
        }
        // if (people.has_qq()) {

        // } else if (people.has_wechat()) {

        // }
        switch (people.other_contact_case()) // 返回一个枚举类型
        {
            case contacts2::PeopleInfo::OtherContactCase::kQq:
                std::cout << "qq: " << people.qq() << std::endl;
                break;
            case contacts2::PeopleInfo::OtherContactCase::kWechat:
                std::cout << "wechat: " << people.wechat() << std::endl;
                break;
            default:
                break;
        }
        if (people.remark_size())
        {
            std::cout << "备注信息：" << std::endl;
        }
        for (auto it = people.remark().cbegin(); it != people.remark().cend(); it++)
        {
            std::cout << "   " << it->first << ": " << it->second << std::endl;
        }
    }
}


int main()
{
    contacts2::Contacts contacts;
    // 1. 读取本地已存在的通讯录文件
    // protobuf序列化后的结果是二进制序列
    std::fstream input("contacts.bin", std::ios::in | std::ios::binary);
    if (!contacts.ParseFromIstream(&input))
    {
        // 反序列化失败
        std::cerr << "parse error!" << std::endl;
        input.close();
        return -1;
    }
    // 2. 打印通讯录联系人
    PrintContacts(contacts);
    input.close();
    return 0;
}